import jwt
import time
from Static import Static


class TokenHelper:
    def __init__(self):
        self.ALGORITHM = "HS256"
        self.TOKEN_EXPIRE_TIME = 60 * 60 * 2  # token有效时间2小时

    def generateJwtToken(self, username):
        payload = {
            "username": username,
            "exp": int(time.time()) + self.TOKEN_EXPIRE_TIME,
        }
        token = jwt.encode(payload, Static.SYSTEM_KEY_SECRET, algorithm=self.ALGORITHM)
        return token

    def verifyToken(self, token):
        """验证用户token"""
        try:
            _payload = jwt.decode(
                token, Static.SYSTEM_KEY_SECRET, algorithms=[self.ALGORITHM]
            )
        except jwt.PyJWTError:
            print("token解析失败")
            return False
        else:
            exp = int(_payload.pop("exp"))
            if time.time() > exp:
                print("token已超时失效")
                return False
        return _payload.pop("username")
